from exts import sendEmail
from models import User
from wmxy import wmxy
import time
import config
import urllib.parse

userpage = open("static/userpage.html", "r", encoding="utf-8")  # 读取文件
userpage = userpage.read()

adminpage = open("static/adminpage.html", "r", encoding="utf-8")  # 读取文件
adminpage = adminpage.read()


def getAllUserDB():
    list = User.query.all()
    res = {}
    for user in list:
        res[user.sno] = user
    return res


# 学生时钟：逐个提醒打卡
def ClockUser(adminName):
    admin = wmxy(config.ADMIN_USERNAME, config.ADMIN_PASSWORD)
    if not admin.login():
        print("登录失败：" + admin.errmsg)
    else:
        userDB = getAllUserDB()
        _list = admin.list2(deptId=config.DEPTID)
        stuList = []
        for item in _list:
            stuNo = item['stuNo']
            if stuNo in userDB:
                stuList.append({'sno': userDB[stuNo].sno, 'email': userDB[stuNo].email, 'name': item['name'],
                                'isRss': userDB[stuNo].isRss})

        stuText = ''
        len_StuList = len(stuList)
        if len_StuList < 1:
            return
        stuList.sort(key=lambda x: x["sno"])
        for index in range(len_StuList):
            stuText += stuList[index]['sno'][-2:] + ' ' + stuList[index]['name']
            if (index + 1) % 3 == 0:
                stuText += '<br>'
            else:
                stuText += ' '

        if adminName:
            signdesc = '本次提醒由班级管理员[' + adminName + ']发起'
        else:
            signdesc = '本次提醒由系统自动发起'

        content = userpage
        content = content.replace("{{ neversignnum }}", str(len_StuList))
        content = content.replace("{{ neversignlist }}", stuText)
        content = content.replace("{{ signdesc }}", signdesc)
        content = content.replace("{{ signtime }}", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

        for item in stuList:
            emailContent = content
            if (item['isRss'] == 1) & (isinstance(item['email'], str)) & (item['email'] != ''):
                emailContent = emailContent.replace("{{ sno }}", item['sno'])
                sendEmail(subject=item['name'] + "同学！完美校园该打卡啦！",
                          content=emailContent,
                          reciever=item['email'])


# 管理员时钟：发送打卡情况名单给管理员
def ClockAdmin(adminList):
    admin = wmxy(config.ADMIN_USERNAME, config.ADMIN_PASSWORD)
    if not admin.login():
        print("登录失败：" + admin.errmsg)
    else:
        _list2 = admin.list2(deptId=config.DEPTID)
        neverSignList = []  # 未打卡名单
        for item in _list2:
            neverSignList.append({
                'sno': item['stuNo'],
                'name': item['name']
            })

        # 未打卡名单 数组转文本回显
        stuText = ''
        len_StuList = len(neverSignList)
        if len_StuList > 0:
            neverSignList.sort(key=lambda x: x["sno"])
            for index in range(len_StuList):
                stuText += neverSignList[index]['sno'][-2:] + " " + neverSignList[index]['name']
                if (index + 1) % 4 == 0:
                    stuText += '<br>'
                else:
                    stuText += ' '

        SignErrorText = ""  # 打卡有误名单
        SignErrorNum = 0  # 打卡有误人数
        _listObject = admin.listObject(deptId='118889')
        for item in _listObject:
            res = CheckForm(item)
            if res:
                res += '<br>'
                SignErrorText += res
                SignErrorNum += 1

        signdesc = '暂无备注..'
        content = adminpage
        content = content.replace("{{ neversignnum }}", str(len_StuList))
        content = content.replace("{{ neversignlist }}", stuText)
        content = content.replace("{{ signdesc }}", signdesc)
        content = content.replace("{{ signtime }}", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

        content = content.replace("{{ signerrornum }}", str(SignErrorNum))
        content = content.replace("{{ signerrorlist }}", SignErrorText)
        for info in adminList:
            emailContent = content
            emailContent = emailContent.replace("{{ adminEmail }}", info['email'])
            emailContent = emailContent.replace("{{ adminName }}", urllib.parse.quote(info['name']))

            sendEmail(subject="最新打卡名单[" + time.strftime('%H时%M分', time.localtime(time.time())) + "]",
                      content=emailContent,
                      reciever=info['email'])


def CheckForm(form):
    username = form['username']
    resText = username

    # 体温，小于37.3
    if float(form['temperature']) > 37.3:
        resText += '-[体温](' + form['temperature'] + ')'

    # 当天有无乏力、干咳等不适症状？
    if form['isConfirmed'] != '否':
        resText += '-[乏力、干咳](' + form['isConfirmed'] + ')'

    # 当天是否发热(体温大于37.3°c为发热)
    if form['sfwz2'] != '否':
        resText += '-[发热](' + form['sfwz2'] + ')'

    # 当天是否与不明病因发热和咳嗽病例密切接触？
    if form['isdefinde'] != '否':
        resText += '-[接触发热咳嗽](' + form['isdefinde'] + ')'

    # 当天是否与新冠肺炎无症状感染者、疑似和确认患者密切接触？
    if form['jtcy'] != '否':
        resText += '-[接触新冠](' + form['jtcy'] + ')'

    # 当天是否食用、接触野生动物？
    if form['isGoWarningAdress'] != '否':
        resText += '-[接触野生](' + form['isGoWarningAdress'] + ')'

    # 当天微信申报粤康码是否为红码？
    if form['isTouch'] != '否':
        resText += '-[红码](' + form['isTouch'] + ')'

    # 当天身体健康状况？
    if form['isTransitArea'] != '健康良好':
        resText += '-[健康状况](' + form['isTransitArea'] + ')'

    # 当天是否有到中高风险地区的旅行史或居住史？
    if form['isTransitProvince'] != '否':
        resText += '-[风险旅行](' + form['isTransitProvince'] + ')'
        # 如果是，请填写情况（旅居时间段，在中高风险地区住宿和经过地点，同行人员）
        resText += '-[旅行详情](' + form['age'] + ')'

    # 当天是否患未治愈传染病或其他疾病（若是注明疾病名称）
    if (form['isFFHasSymptom'] != "") & (form['isFFHasSymptom'] != '否'):
        resText += '-[患病](' + form['isFFHasSymptom'] + ')'
        # 如果是，请填写情况（旅居时间段，在中高风险地区住宿和经过地点，同行人员）
        resText += '-[病名](' + form['assphonenum'] + ')'

    if resText == username:
        # 没有异常
        return ''
    else:
        # 数据异常
        return resText
